package com.aquila.bible.activity;

import java.text.ParseException;
import java.util.Calendar;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aquila.bible.MyBaseActivity;
import com.aquila.bible.R;
import com.aquila.bible.SearchResultObject;
import com.aquila.bible.system.SystemConfig;
import com.aquila.bible.utils.BookShelfUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

/**
 * 
 * 2.0更新要点
 * 1、程序名更改为《圣经(HolyBible)》
 * 2、修正搜索经文范围选择（教会历史 和 启示录）时的搜索异常
 * 3、解决意见反馈逢单日而无法发送的异常
 * 4、添加了书签功能，以后可以随时记录自己喜欢的经文。
 * 5、优化了阅读经文界面字体大小个性化设置
 * 
 * 2.1版计划更新要点
 * 1、章节选择流程修改，改为先进入章节选择页面
 * 2、增加浏览历史的功能
 * 3、开通设置(a、滚动速度，b、)
 * 4、修正进入下一章的显示到第一节
 * 5、搜索显示优化
 * 6、发送短信加上书卷名
 * 
 * @author tc003166
 *
 */


public class HolyBibleActivity extends MyBaseActivity implements OnClickListener{
	
//	private TextView titleTextView ;
	private Button newButton, oldButton ;
//	private View historyButton ;
	private View searchButton ;
	private LinearLayout contentLayout ;
	
	private LinearLayout menuLayout ;
	private PopupWindow pop ;
	
	private LinearLayout newLayout, oldLayout ;
	
	private TextView lastReadTextView ;
	private TextView startCountTextView ;
	
//	private LinearLayout searchLayout ;
//	private LinearLayout historyLayout ;
	
	private Animation inLeftAnimation ;
	private Animation inRightAnimation ;
	private Animation outLeftAnimation ;
	private Animation outRightAnimation ;
	
	private int viewId = 2 ;
//	ListBookAdapter oldAdapter ;
//	ListBookAdapter newAdapter ;
	
	/** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bookshelf_layout);
        newButton = (Button) findViewById(R.id.btn_new_testament) ;
        oldButton = (Button) findViewById(R.id.btn_old_testament) ;
        lastReadTextView = (TextView) findViewById(R.id.tv_last_read) ;
        startCountTextView = (TextView) findViewById(R.id.tv_start_count) ;
        searchButton = findViewById(R.id.btn_search) ;
        contentLayout = (LinearLayout) findViewById(R.id.content_layout) ;
        newLayout = (LinearLayout) layoutInflater.inflate(R.layout.view_main_content_layout, null) ;
        oldLayout = (LinearLayout) layoutInflater.inflate(R.layout.view_main_content_layout, null) ;
        
        
        inLeftAnimation = AnimationUtils.loadAnimation(context, R.anim.translate_in_from_left) ;
        inRightAnimation = AnimationUtils.loadAnimation(context, R.anim.translate_in_from_right) ;
        outLeftAnimation = AnimationUtils.loadAnimation(context, R.anim.translate_out_to_left) ;
        outRightAnimation = AnimationUtils.loadAnimation(context, R.anim.translate_out_to_right) ;
        
        SystemConfig.sp = getSharedPreferences("my_config", MODE_PRIVATE) ;
        SystemConfig.editor = SystemConfig.sp.edit() ;
        
        
        SystemConfig.testamentNameStrings = getResources().getStringArray(R.array.jiuyue) ;
        SystemConfig.testamentShortStrings= getResources().getStringArray(R.array.jiuyue_jianchen) ;
        SystemConfig.testamentchapterCount= getResources().getStringArray(R.array.jiuyue_zhangshu) ;
        
        newButton.setOnClickListener(this) ;
        oldButton.setOnClickListener(this) ;
        searchButton.setOnClickListener(this) ;
        initOldTestamentItems() ;
        initNewTestamentItems() ;
        
        
        initPopupMenu() ;
        contentLayout.addView(oldLayout) ;
        contentLayout.addView(newLayout) ;
        
        newLayout.setVisibility(View.GONE) ;
        MobclickAgent.onEvent(this, "1") ;
        
        
        setPrompt() ;
        if (SystemConfig.sp.getBoolean("homePrompt", true)) {
        	showPrompt() ;
        }
        
//        if (!SystemConfig.isCheckNewVerson) {
//        	checkNewVerson() ;
//        	SystemConfig.isCheckNewVerson = true ;
//        }
      //友盟的自动更新，待处理
//		UmengUpdateAgent.update(this) ;
        
    }
    
    
    /**
     * 首页启动的对话框
     *2012-8-2 上午10:20:49
     */
    private void setPrompt(){
    	boolean isAlwaysClose = SystemConfig.sp.getBoolean("isAlwaysClose", false) ;
    	if (isAlwaysClose) {
    		return ;
    	}
    	int startCount = SystemConfig.sp.getInt("startCount", 0) ;
    	boolean isClosePrompt = SystemConfig.sp.getBoolean("isClosePrompt", false) ;
    	Calendar calendar = Calendar.getInstance() ;
    	String dateString = SystemConfig.sp.getString("closeDate", null) ;
    	if (dateString != null) {
    		try {
    			calendar.setTime(SystemConfig.sdf_1.parse(dateString)) ;
    			if (calendar.getTimeInMillis() / 86400000 + 7 <= Calendar.getInstance().getTimeInMillis() / 86400000) {
    				isClosePrompt = false ;
    			}
    			else {
    				isClosePrompt = true ;
    			}
    			
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    	}
    	startCount++ ;
//    	if (startCount >= 5 && !isClosePrompt) {
//    		showHomeDialog(startCount) ;
//    	}
//    	else if ((startCount % 50) == 0) {
//    		showHomeDialog(startCount) ;
//    	}
    	StringBuffer sb = new StringBuffer(); 
    	sb.append("您的程序共开启了<b><font color=#951ea0 >" +startCount+"</font></b>次") ;
    	if (startCount > 30) {
    		sb.append(",再次感谢您对本软件一直以来的支持,愿主大大的祝福你。") ;	
		}
    	startCountTextView.setText(Html.fromHtml(sb.toString())) ;

    	SystemConfig.editor.putInt("startCount", startCount) ;
    	SystemConfig.editor.putBoolean("isClosePrompt", isClosePrompt) ;
    	SystemConfig.editor.commit() ;
    	
    }
    
    
    /**
	 * 操作提示对话框
	 *2012-8-13 下午4:22:02
	 */
	private void showPrompt(){
		
		Builder builder = new Builder(context);
		
		builder.setTitle("更新提示")
		.setMessage("更新要点:\n 1、程序名更改为《圣经(HolyBible)》" +
				"\n 2、修正搜索经文范围选择（教会历史 和 启示录）时的搜索异常" +
				"\n 3、解决意见反馈逢单日而无法发送的异常" +
				"\n 4、添加了书签功能，以后可以记录自己喜爱的经文"
				)
		.setPositiveButton("不再提醒", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SystemConfig.editor.putBoolean("homePrompt", false) ;
				SystemConfig.editor.commit() ;
				dialog.dismiss() ;
			}
		})
		.setNegativeButton("我知道了", null)
		.create().show() ;
	}
	
    
    @Override
    protected void onStart() {
    	super.onStart();
    	String lastRead = SystemConfig.sp.getString("readInfo", null) ;
    	String readTime = SystemConfig.sp.getString("lastReadTime", null) ;
    	if (lastRead == null) {
    		lastReadTextView.setVisibility(View.GONE) ;
    	}
    	else {
    		lastReadTextView.setVisibility(View.VISIBLE) ;
    		lastReadTextView.setText(Html.fromHtml(readTime + lastRead)) ;
    	}
    	
    	
    }
    
    /**
     * 
     * @param startCount
     *2012-8-2 上午9:59:47
     */
    private void showHomeDialog(int startCount){
    	Builder builder = new Builder(context) ;
    	builder.setTitle(R.string.home_start_prompt)
    	.setMessage("感谢主，您启动本程序已经有" +startCount+"次了,为了使本程序今后的版本有更好的用户体验，需要您的奉献支持，是否同意？\n此启动提示可在设置中关闭。")
    	.setPositiveButton(R.string.go_sanctify, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				gotoSanctifyActivity() ;
			}
		})
		.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss() ;
			}
		})
		.create().show() ;
    	
    	
    }
    
    
    int index = 0;
    /***
     * 加载显示新约
     *2012-7-26 下午3:36:08
     */
    private void initNewTestamentItems(){
    	newLayout.removeAllViews() ;
    	for (int i = 13; i < 22; i++) {
    		RelativeLayout layout = (RelativeLayout) layoutInflater.inflate(R.layout.public_bookshelf_layout, null) ;
    		BookShelfUtil shelfUtil = new BookShelfUtil(layout) ;
			for (int j = 0; j < 3; j++) {
				LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.chapter_layout, null) ;
				TextView textView = (TextView) linearLayout.findViewById(R.id.tv_chapter) ;
				TextView shortTextView = (TextView) linearLayout.findViewById(R.id.tv_chapter_for_short) ;
				TextView chapterCountTextView = (TextView) linearLayout.findViewById(R.id.tv_total_chapters) ;
				index = i*3+j ;
				final int clickIndex = i*3+j ;
				textView.setText(SystemConfig.testamentNameStrings[index]) ;
				shortTextView.setText(SystemConfig.testamentShortStrings[index]) ;
				chapterCountTextView.setText("共" + SystemConfig.testamentchapterCount[index] +"章") ;
				switch (j) {
				case 0:
					shelfUtil.addFirstView(linearLayout) ;
					break;
				case 1:
					shelfUtil.addSecondView(linearLayout) ;
					break;
				case 2:
					shelfUtil.addThirdView(linearLayout) ;
					break;

				default:
					break;
				}
				
				linearLayout.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						clickBookGoToRead(clickIndex) ;
					}
				}) ;
			}
			newLayout.addView(layout) ;
		}
    	
    }
    
    
    /**
     * 点击阅读
     * @param clickIndex
     *2012-7-31 下午2:23:08
     */
    private void clickBookGoToRead(int clickIndex){
    	
    	Intent intent = new Intent() ;
		intent.setClass(context, ChapterActivity.class) ;
//		ReadHistoryObject readHistoryObject = new ReadHistoryObject() ;
		SearchResultObject object = new SearchResultObject() ;
		object.setBookString(SystemConfig.testamentNameStrings[clickIndex]) ;
		object.setBookShortString(SystemConfig.testamentShortStrings[clickIndex]) ;
		object.setBookIndex(clickIndex + 1) ; 
		object.setChapterIndex(1) ;
		object.setChapterCount(Integer.parseInt(SystemConfig.testamentchapterCount[clickIndex])) ;
		Bundle bundle = new Bundle() ;
		bundle.putSerializable("object", object) ;
		intent.putExtras(bundle) ;
		intent.putExtra("isSelecte", false) ;
		startActivity(intent) ;
//		overridePendingTransition(R.anim.scale_zoom_in, R.anim.normal) ;
    	
    }
    
    
    /**
     * 加载显示旧约
     *2012-7-27 下午3:51:10
     */
    private void initOldTestamentItems(){
    	oldLayout.removeAllViews() ;
    	for (int i = 0; i < 13; i++) {
    		RelativeLayout layout = (RelativeLayout) layoutInflater.inflate(R.layout.public_bookshelf_layout, null) ;
    		BookShelfUtil shelfUtil = new BookShelfUtil(layout) ;
    		for (int j = 0; j < 3; j++) {
    			LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.chapter_layout, null) ;
    			TextView textView = (TextView) linearLayout.findViewById(R.id.tv_chapter) ;
    			TextView shortTextView = (TextView) linearLayout.findViewById(R.id.tv_chapter_for_short) ;
    			TextView chapterCountTextView = (TextView) linearLayout.findViewById(R.id.tv_total_chapters) ;
    			
    			index = i*3+j ;
    			final int clickIndex = i*3+j ;
    			textView.setText( SystemConfig.testamentNameStrings[index]) ;
    			shortTextView.setText(SystemConfig.testamentShortStrings[index]) ;
    			chapterCountTextView.setText("共" + SystemConfig.testamentchapterCount[index] +"章") ;
    			
    			switch (j) {
    			case 0:
    				shelfUtil.addFirstView(linearLayout) ;
    				break;
    			case 1:
    				shelfUtil.addSecondView(linearLayout) ;
    				break;
    			case 2:
    				shelfUtil.addThirdView(linearLayout) ;
    				break;
    				
    			default:
    				break;
    			}
    			
    			linearLayout.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						clickBookGoToRead(clickIndex) ;
					}
				}) ;
    		}
    		oldLayout.addView(layout) ;
    	}
    	
    }
    
    /***
     * 点击事件的字体颜色的处理
     * @param index
     *2012-7-27 下午3:51:34
     */
    private void clickTypeColor(int index){
    	newButton.setTextColor(0xff6c300e) ;
    	oldButton.setTextColor(0xff6c300e) ;
//    	historyButton.setTextColor(0xff888888) ;
    	switch (index) {
		case 0:
			newButton.setTextColor(0xffffffff) ;
			break;
		case 1:
			oldButton.setTextColor(0xffffffff) ;
			break;
//		case 2:
//			historyButton.setTextColor(0xffffffff) ;
//			break;

		default:
			break;
		}
    	
    }

    private LinearLayout menuItemLayout1 ;
    private LinearLayout menuItemLayout2 ;
    private LinearLayout menuItemLayout3 ;
    private LinearLayout menuItemLayout4 ;
    private LinearLayout menuItemLayout5 ;
    /**
     * 初始化菜单的布局
     *2012-7-27 下午3:58:55
     */
    private void initPopupMenu(){
        menuLayout = (LinearLayout) layoutInflater.inflate(R.layout.menu_at_home_page, null) ;
        pop = new PopupWindow(menuLayout, LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);// menu菜单获得焦点 如果没有获得焦点menu菜单中的控件事件无法响应
        pop.update();
        pop.setAnimationStyle(R.style.PopupAnimation) ;
    	
        menuLayout.setFocusableInTouchMode(true) ;
        menuLayout.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_MENU) {
					pop.dismiss() ;
					return true ;
				}
				return false;
			}
		}) ;
        
        menuItemLayout1 = (LinearLayout) menuLayout.findViewById(R.id.menu_item_01) ;
        menuItemLayout2 = (LinearLayout) menuLayout.findViewById(R.id.menu_item_02) ;
        menuItemLayout3 = (LinearLayout) menuLayout.findViewById(R.id.menu_item_03) ;
        menuItemLayout4 = (LinearLayout) menuLayout.findViewById(R.id.menu_item_04) ;
        menuItemLayout5 = (LinearLayout) menuLayout.findViewById(R.id.menu_item_05) ;
        
        menuItemLayout1.setOnClickListener(this) ;
        menuItemLayout2.setOnClickListener(this) ;
        menuItemLayout3.setOnClickListener(this) ;
        menuItemLayout4.setOnClickListener(this) ;
        menuItemLayout5.setOnClickListener(this) ;
        
    	
    	
    }
    
    
    
    
    
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add("item") ;
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
    	if (pop != null) {
    		if (pop.isShowing()) {
				pop.dismiss() ;
			}
    		else {
    			pop.showAtLocation(menuLayout, Gravity.BOTTOM, 0, 0) ;
			}
    	}
    
    	return false ; //super.onMenuOpened(featureId, menu);
    }
    
    
    /**
     * 点击的显示的视图和动画特效
     * @param clickId
     *2012-7-31 上午9:44:33
     */
    private void clickViewDisplay(int clickId){
    	if (clickId == viewId) {
			return ;
		}
    	
    	switch (this.viewId) {
			case 1:
//				historyLayout.setVisibility(View.GONE) ;
//				historyLayout.startAnimation(outLeftAnimation) ;
				break;
			case 2:
				oldLayout.setVisibility(View.GONE) ;
				if (clickId > viewId) {
					oldLayout.startAnimation(outLeftAnimation) ;
				}
				else {
					oldLayout.startAnimation(outRightAnimation) ;
				}
				break;
			case 3:
				newLayout.setVisibility(View.GONE) ;
				if (clickId > viewId) {
					newLayout.startAnimation(outLeftAnimation) ;
				}
				else {
					newLayout.startAnimation(outRightAnimation) ;
				}
				break;
//			case 4:
//				searchLayout.setVisibility(View.GONE) ;
//				searchLayout.startAnimation(outRightAnimation) ;
//				break;
			}
    	
    	switch (clickId) {
	    	case 1:
//				historyLayout.setVisibility(View.VISIBLE) ;
//				historyLayout.startAnimation(inLeftAnimation) ;
				break;
			case 2:
				oldLayout.setVisibility(View.VISIBLE) ;
				if (clickId > viewId) {
					oldLayout.startAnimation(inRightAnimation) ;
				}
				else {
					oldLayout.startAnimation(inLeftAnimation) ;
				}
				break;
			case 3:
				newLayout.setVisibility(View.VISIBLE) ;
				newLayout.startAnimation(inRightAnimation) ;
//				if (clickId > viewId) {
//				}
//				else {
//					newLayout.startAnimation(inLeftAnimation) ;
//				}
				break;
//			case 4:
//				searchLayout.setVisibility(View.VISIBLE) ;
//				searchLayout.startAnimation(inRightAnimation) ;
//				break;
		}
    	viewId = clickId ;
    	
    }
    
    /**
     * 去奉献的界面
     *2012-8-2 上午9:53:10
     */
    private void gotoSanctifyActivity(){
    	Intent intent = new Intent() ;
		intent.setClass(context, SanctifyActivity.class) ;
		startActivity(intent) ; 
    }
    
    @Override
    public void onClick(View v) {
    	if ( v == newButton) {
    		clickViewDisplay(3) ;
    		clickTypeColor(0) ;
    		MobclickAgent.onEvent(this, "2") ;
    	}
    	else if (v == oldButton) {
    		clickViewDisplay(2) ;
    		clickTypeColor(1) ;
    		MobclickAgent.onEvent(this, "3") ;
		}
//    	else if (v == historyButton) {
//    		clickViewDisplay(1) ;
//    		showToast("点击测试", false) ;
//    		MobclickAgent.onEvent(this, "11") ;
//		}
    	else if (v == searchButton) {
    		Intent intent = new Intent() ;
    		intent.setClass(context, SearchActivity.class) ;
    		startActivity(intent) ;
    		overridePendingTransition(R.anim.translate_in_from_right, R.anim.translate_out_to_left) ;
    		MobclickAgent.onEvent(this, "4") ;
    	}
    	else if (v == menuItemLayout1) {
	    	Intent intent = new Intent() ;
	    	intent.setClass(context, FeedBackActivity.class) ;
	    	startActivity(intent) ;
	    	MobclickAgent.onEvent(this, "6") ;
		}
    	else if (v == menuItemLayout2) {
    	Intent intent = new Intent() ;
    	intent.setClass(context, CollectionActivity.class) ;
    	startActivity(intent) ;
    	
    	}
    	else if (v == menuItemLayout3) { //设置
    		showToast("此功能正在开发中，如果您有什么地方需要个性化设置的，请在反馈中告知我，我会尽快加上。", true) ;
//    		Intent intent = new Intent() ;
//    		intent.setClass(this, SettingActivity.class) ;
//    		startActivity(intent) ;
    	}
    	else if (v == menuItemLayout4) {
    		showToast("由于开发时间有限，此功能暂未开通，会尽快在下一版本完善，敬请耐心等待。", false) ;
//    		gotoSanctifyActivity() ;   		
    	}
    	else if (v == menuItemLayout5) {
    		Intent intent = new Intent() ;
			intent.setClass(context, AboutActivity.class) ;
			startActivity(intent) ;
			MobclickAgent.onEvent(this, "10") ;
    	}
    	
    	if (pop!= null && pop.isShowing()) {  
			pop.dismiss() ;
		}
    }
    
    private void showExitDialog(){
    	Builder builder = new Builder(this) ;
    	builder.setTitle("确定退出？")
    	.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish() ;
			}
		})
		.setNegativeButton("取消", null)
		.create().show() ;
    	
    }
    
    @Override
    public void onBackPressed() {
    	showExitDialog() ;
    }
    
}